package net.rock.eshop.controller;

import net.rock.eshop.entity.Book;
import net.rock.eshop.entity.Category;
import net.rock.eshop.exception.ResourceNotFoundException;
import net.rock.eshop.service.BookService;
import net.rock.eshop.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/fetch")
    public Book fetchBookById(int id) {
        Book book = bookService.fetchBookById(id);
        if (book != null) {
            return book;
        } else {
            throw new ResourceNotFoundException();
        }
    }

    @GetMapping("/list")
    public List<Book> fetchBooks(
            @RequestParam(required = false) Integer category,
            @RequestParam(required = false) Integer page
    ) {
        if (category != null && category == 0) {
            category = null;
        }
        return bookService.fetchBooks(category, page);
    }

    @GetMapping("/fetchCategories")
    public List<Category> fetchCategories() {
        return categoryService.fetchAllCategories();
    }

    @GetMapping("/search")
    public List<Book> searchBooks(String keyword){
        return bookService.searchBooks(keyword);
    }

    @GetMapping("/fetchCategory")
    public String fetchCategoryById(int id) {
        return categoryService.fetchCategoryById(id).getName();
    }
}
